package com.ycy.controller.excel;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ycy.pojo.Employee;
import com.ycy.service.employee.EmployService;
import com.ycy.util.ExcelUtil;

@Controller
public class ExportExcelController {
	@Autowired
	EmployService employservice;
	@ResponseBody
	@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
		  String filename = "employee.xls";
	        String sheetName = "sheet1";
	    	List<Employee> employees=employservice.findAll();
	    	 String[] title = {"ID", "姓名", "昵称", "部门", "工资", "工号"};
	        String[][] content = new String[employees.size()][6]; try {
	            for (int i = 0; i < employees.size(); i++) {
	                content[i][0] = String.valueOf(employees.get(i).getId());
	                content[i][1] = employees.get(i).getName();
	                content[i][2] = employees.get(i).getNickname();
	                content[i][3] = employees.get(i).getSection();
	                content[i][4] = String.valueOf(employees.get(i).getSalary());
	                content[i][5] = employees.get(i).getJobNumber();
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
	        try {
	            // 响应到客户端
	            this.setResponseHeader(response, filename);
	            OutputStream os = response.getOutputStream();
	            wb.write(os);
	            os.flush();
	            os.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		// TODO Auto-generated method stub
		 try {
	            try {
	                fileName = new String(fileName.getBytes(), "UTF-8");
	            } catch (UnsupportedEncodingException e) {
	                e.printStackTrace();
	            }
	            response.setContentType("application/vnd.ms-excel");
	            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        }
	}

}
